/*
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is ST_EXT-S_UIMAST.
 *
 * The Initial Developer of the Original Code is
 * University of Rome, Tor Vergata
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 */

/**
 * Loads an XML file given its URI. It understands several schemes: 
 * http, https, file, chrome, ftp; it can work either on local files
 * or on remote ones. Since it is synchonous, you should not use it
 * to connect to a real remote server to avoid UI freeze.
 * @param uri the URI identifying the file to load
 * @return the file content or null if an error happens
 */
function loadXMLFile(uri)
{
	// Performs the actual call
	// Gets an instance of XMLHttpRequest
	var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
	                    .createInstance(Components.interfaces.nsIXMLHttpRequest);
	                              
	// Opens the conncetions
	req.open("GET",uri,false);	// synchronous
	
	// Every configuration afert "open" but before "send"
	// Forces text/xml mime-type
	req.overrideMimeType('text/xml');
	
	// Closes the connection after the request
	req.setRequestHeader("connection","close");
	
	// By-passes cache
	req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;

	// Sends the request
	req.send(null);
	
	// We cannot check (req.status) == 200 on local file
	return req.responseXML;
}

/**
 * Extracts an eventual error message from a response. 
 * @param reponse the XML response
 * @return the error message or null if there isn'one.
 *         to check if there is an error use the
 *         operator === (equals and same type) to avoid
 *         empty string match null
 */
function getErrorMessage(response)
{
	// Gets the <Tree> tag
	var tree = response.getElementsByTagName("Tree")[0];
		
	// Checks if it is an error
	if(tree.getAttribute("type") == "error") {
		// if it is an error
		
		// Gets the <Error> child
		var error = tree.getElementsByTagName("Error")[0];
		
		// Gets the error message
		var message = error.getAttribute("value");
		
		// Returns the error message (if this attribute isn't set, produces "Unknown Error");
		return ( message || "Unknown Error" );
	}
	
	return null;	
}
